package com.ndp.fb.fbagent.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.dubbo.config.annotation.Service;
import com.ndp.fb.constant.CommonConstants;
import com.ndp.fb.fbagent.service.AdGroupFBService;
import com.ndp.fb.model.fbagent.param.APIPriority;
import com.ndp.fb.model.fbagent.param.ApiCallBackTarget;
import com.ndp.fb.model.fbagent.param.adgroup.AdGroupParam;
import com.ndp.fb.model.fbagent.result.FacebookResult;
import com.ndp.fb.model.fbagent.result.adgroup.FbAdgroup;
import com.restfb.Parameter;

/**
 * Created by Jacky on 2015/2/27.
 */
@Service
public class AdGroupFBServiceImpl extends AbstractFBagentService implements AdGroupFBService {

    @Override
    public void updateAdGroup(String accessToken, Long fbAccountId, AdGroupParam adGroupParam) {
//        uri="/{ad_id}"
        String uri = "/" + adGroupParam.getAdGroupId();
        List<Parameter> parameterList = adapter(adGroupParam);
        makePostRequest(uri, accessToken, parameterList.toArray(new Parameter[]{}));
    }


    @Override
    public String updateAdGroupStats(AdGroupParam adGroupParam) {
        String uri = "/" + adGroupParam.getAdGroupId();
        List<Parameter> parameterList = adapter(adGroupParam);
        return makePostRequest(uri, adGroupParam.getAccessToken(), parameterList.toArray(new Parameter[]{}));
    }

    @Override
    public void updateAdGroupStatsAsyn(AdGroupParam adGroupParam) {
        String uri = "/" + adGroupParam.getAdGroupId();
        List<Parameter> parameterList = adapter(adGroupParam);
        makePostRequest(uri, adGroupParam.getAccessToken(), parameterList.toArray(new Parameter[]{}));
    }

    @Override
    public Long getAdGroupSumaryByAccount(String accessToken, Long fbAccountId) {
        AdGroupParam requestParam = new AdGroupParam();
//        requestParam.setSummary("true"); //todo verify
        requestParam.setFbAccountId(fbAccountId);
        requestParam.setApiPriorityCode(APIPriority.FetchAdcampaignsCount.getCode());
        List<Parameter> parameterList = adapter(requestParam);
        String uri = "/act_" + fbAccountId + "/ads";
        FacebookResult<FbAdgroup> result = fetchFacebookResult(uri, accessToken, parameterList, false,
                0, CommonConstants.NUM_INT_1, FbAdgroup.class);
        return result.getSummary().getTotalCount();
    }

    @Override
    public void getAdGroupById(String accessToken, Long accountId, Long adGroupId) {
        //升级api2.5,
        String fields = "account_id,status,objective,bid_type,bid_info,adset_id,campaign_id,conversion_specs,created_time,creative,ad_review_feedback," +
                "id,name,targetingsentencelines,tracking_specs,updated_time";
        Map<String, String> equipment = new HashMap<>();
        equipment.put("entrustAccountId", accountId + "");
        equipment.put("accessToken", accessToken);
        AdGroupParam requestParam = new AdGroupParam();
        requestParam.setFields(fields);
        requestParam.setApiPriorityCode(APIPriority.FetchAdgroupBusiness.getCode());
        requestParam.setEquipment(equipment);
        requestParam.setApiCallbackTargetType(ApiCallBackTarget.PublishResource.FetchOneAdGroup.getTargetType());
        requestParam.setCallBack(true);
        requestParam.setFbAccountId(accountId);
        Parameter[] parameters = this.adapterArray(requestParam);
        String uri = "/" + adGroupId;
        makeGetRequest(uri, accessToken, parameters);

    }

    @Override
    public void getAdGroupByAccount(AdGroupParam adGroupParam)
    {
        List<Parameter> parameterList = adapter(adGroupParam);
        String uri = "/act_" + adGroupParam.getFbAccountId() + "/ads";
        makeGetRequest(uri, adGroupParam.getAccessToken(), parameterList.toArray(new Parameter[]{}));
    }


    @Override
    public void createAdGroup(AdGroupParam adGroupParam) {
        String url = "/act_" + adGroupParam.getFbAccountId() + "/ads";
        Parameter[] parameters = this.adapterArray(adGroupParam);
        makePostRequest(url, adGroupParam.getAccessToken(), parameters);
    }



    @Override
    public void getAllAdGroupByAccountv2_4(Map<String, String> equipmentMap) {
        String fields = "account_id,ad_review_feedback,adlabels,adset{account_id,adlabels,adset_schedule,bid_amount,bid_info,billing_event,budget_remaining,campaign_id,configured_status,created_time,creative_sequence,daily_budget,effective_status,end_time,frequency_cap,frequency_cap_reset_period,frequency_control_specs,is_autobid,lifetime_budget,lifetime_frequency_cap,lifetime_imps,name,optimization_goal,pacing_type,promoted_object,rf_prediction_id,rtb_flag,start_time,targeting,updated_time,use_new_app_click},adset_id,bid_amount,bid_info,bid_type,campaign{account_id,adlabels,buying_type,can_use_spend_cap,configured_status,created_time,effective_status,id,name,objective,spend_cap,start_time,stop_time,updated_time},campaign_id,configured_status,conversion_specs,created_time,creative{actor_id,actor_image_hash,actor_image_url,actor_name,adlabels,applink_treatment,body,call_to_action_type,image_crops,image_hash,image_url,instagram_actor_id,instagram_permalink_url,instagram_story_id,object_story_spec,object_id,object_story_id,object_type,object_url,run_status,product_set_id,template_url,thumbnail_url,url_tags,title,link_url,name,id,link_og_id,platform_customizations},effective_status,last_updated_by_app_id,name,tracking_specs,updated_time";
        AdGroupParam requestParam = new AdGroupParam();
        requestParam.setFields(fields);
        requestParam.setLimit(CommonConstants.NUM_INT_100);
        requestParam.setApiPriorityCode(APIPriority.FetchAdgroupBusiness.getCode());
        requestParam.setEquipment(equipmentMap);
        requestParam.setApiCallbackTargetType(ApiCallBackTarget.SyncBusiness.SyncAdGroupV2_4.getTargetType());
        requestParam.setCallBack(true);
        if(StringUtils.isNotEmpty(equipmentMap.get("after"))){
        	requestParam.setAfter(equipmentMap.get("after"));
        }
        requestParam.setFbAccountId(Long.valueOf(equipmentMap.get("entrustAccountId")));
        requestParam.setFiltering(equipmentMap.get("filtering"));
        requestParam.setSummary("true");
        Parameter[] parameters = this.adapterArray(requestParam);
        String uri = "/act_" + equipmentMap.get("entrustAccountId") + "/ads";
        makeGetRequest(uri, equipmentMap.get("accessToken"), parameters);

    }

    @Override
    public void getByAdSetId(String accessToken, Long adSetId,AdGroupParam adGroupParam) {
        String fields = "account_id,ad_review_feedback,adlabels,adset{account_id,adlabels,adset_schedule,bid_amount,bid_info,billing_event,budget_remaining,campaign_id,configured_status,created_time,creative_sequence,daily_budget,effective_status,end_time,frequency_cap,frequency_cap_reset_period,frequency_control_specs,is_autobid,lifetime_budget,lifetime_frequency_cap,lifetime_imps,name,optimization_goal,pacing_type,promoted_object,rf_prediction_id,rtb_flag,start_time,targeting,updated_time,use_new_app_click},adset_id,bid_amount,bid_info,bid_type,campaign{account_id,adlabels,buying_type,can_use_spend_cap,configured_status,created_time,effective_status,id,name,objective,spend_cap,start_time,stop_time,updated_time},campaign_id,configured_status,conversion_specs,created_time,creative{actor_id,actor_image_hash,actor_image_url,actor_name,adlabels,applink_treatment,body,call_to_action_type,image_crops,image_hash,image_url,instagram_actor_id,instagram_permalink_url,instagram_story_id,object_story_spec,object_id,object_story_id,object_type,object_url,run_status,product_set_id,template_url,thumbnail_url,url_tags,title,link_url,name,id,link_og_id,platform_customizations},effective_status,last_updated_by_app_id,name,tracking_specs,updated_time";
        adGroupParam.setFields(fields);
        Parameter[] parameters = this.adapterArray(adGroupParam);
        String uri = "/" + adSetId + "/ads";
        makeGetRequest(uri, accessToken, parameters);
    }

    @Override
    public void getOneAdGroupStatus(String accessToken, Long accountId, Long adGroupId, String mongodbId) {
        String fields = "id,effective_status,ad_review_feedback";
        Map<String, String> equipment = new HashMap<>();
        equipment.put("mongodbId", mongodbId);
        AdGroupParam requestParam = new AdGroupParam();
        requestParam.setFields(fields);
        requestParam.setApiPriorityCode(APIPriority.FetchAdgroupBusiness.getCode());
        requestParam.setEquipment(equipment);
        requestParam.setApiCallbackTargetType(ApiCallBackTarget.AdPublish.AuditAdFix.getTargetType());
        requestParam.setReviewFeedbackBreakdown(true);
        requestParam.setCallBack(true);
        requestParam.setFbAccountId(accountId);
        Parameter[] parameters = this.adapterArray(requestParam);
        String uri = "/" + adGroupId;
        makeGetRequest(uri, accessToken, parameters);

    }
}
